package com.beidouapp.message;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


public class AuditLogMessageUtils
{
	public static Map<String, String> messageMap = new HashMap<String, String>();
	public static final String[] files = new String[] { "/META-INF/service/properties/auditTemplate.properties" };
	public static AuditLogMessageUtils messageUtils = null;

	private AuditLogMessageUtils()
	{}

	@SuppressWarnings("rawtypes")
	public static synchronized AuditLogMessageUtils getInstance()
	{
		if (messageUtils == null)
		{
			for (String file : files)
			{
				try
				{
					Resource resource = new ClassPathResource(file);
					Properties props = PropertiesLoaderUtils.loadProperties(resource);
					for (Map.Entry entry : props.entrySet())
					{
						messageMap.put((String) entry.getKey(), (String) entry.getValue());
					}
				}
				catch (IOException e)
				{
					// ignore
					e.printStackTrace();
				}
			}
			messageUtils = new AuditLogMessageUtils();
		}
		return messageUtils;
	}

	public String getMessage(String key, String values)
	{
		String orginal = messageMap.get(key);
		if (null == orginal)
		{
			return null;
		}
		JSONObject jsonObj = JSON.parseObject(values);
		Set<String> keys = jsonObj.keySet();
		for (String keyTmp : keys)
		{
			orginal = orginal.replaceAll("\\{" + keyTmp + "\\}", jsonObj.get(keyTmp).toString());
		}
		return orginal;
	}

	public static void main(String[] args)
	{
		String tmp = "{\"loginname\":\"\",\"username\":\"超级管理员\",\"time\":\"2016-07-22 10:03:05\",\"name\":\"\",\"userid\":0}";
		String ss = AuditLogMessageUtils.getInstance().getMessage("login.success", tmp);
		System.out.println(ss);
	}
}
